<template>
  <n-card :bordered="false" class="proCard table">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
    <BasicTable 
      :columns="columns" 
      :request="loadDataTable" 
      @fetch-success="fetchSuccess"
      ref="actionRef" 
      :actionColumn="actionColumn" 
      :row-key="(row) => row.id"
      :scroll-x="1000">
      <!-- 表格上方左侧的位置 -->
      <template #tableTitle>
        <n-space>
          <!-- 批量删除 -->
          <n-button strong secondary type="error" @click="removeRows">
            批量删除
          </n-button>
        </n-space>
      </template>
    </BasicTable>
    <n-drawer v-model:show="showDetail" :default-width="600" placement="right" resizable>
      <n-drawer-content title="医院详情" closable>
        <HospitalDetail v-model="currentHospId"/>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</template>
<script setup>
import { h, reactive, ref, unref } from 'vue'
import { getHospitalPageList, updateHospStatus } from '@/api/hospital'
import { getDictByDictCode, findChildData } from '@/api/dict'
import { BasicForm, useForm } from '@/components/Form'
import { BasicTable, TableAction } from '@/components/Table'
import { createListColumns, createSchemas, createActions } from './columns';
import { useMessage } from 'naive-ui';
import HospitalDetail from './details.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const message = useMessage()
const actionRef = ref(null)
const currentIndex = ref(1)
const hostypeDictOptions = ref([])
const provinceDictOptions = ref([])
const cityDictOptions = ref([])
const showDetail = ref(false)
const currentHospId = ref('')

const schemas = createSchemas(hostypeDictOptions, provinceDictOptions, cityDictOptions, {
  fetchTypeOptions(show) {
    if (show && hostypeDictOptions.value.length == 0) {
      loadHosTypeData()
    }
  },
  fetchProvinceOptions(show) {
    if (show && provinceDictOptions.value.length == 0) {
      loadProvinceData()
    }
  },
  fetchCityOptions(show) {
    if (show && cityDictOptions.value.length == 0) {
      getCityData()
    }
  }
})

// 注册表单
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:2 m:2 l:3 xl:4 2xl:4' },
  collapsed: false,
  labelWidth: 80,
  schemas,
});
// 表格列属性
const columns = createListColumns({
  currentIndex() {
    return unref(currentIndex);
  },
  switchStatus: async (row) => {
    const { id, status } = row;
    const update = status === 1 ? 0 : 1;
    try {
      await updateHospStatus(id, update)
      row.status = update;
      message.success(update === 1 ? '已上线' : '已下线')
    } catch (error) {
      row.status = status
    }
  },
});

// 表格操作列属性
const actionColumn = reactive({
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(record) {
    return h(TableAction, {
      showLabel: true,
      actions: createActions(record, { handleCat, handleSchedule }),
    });
  },
});


// 数据请求
const loadDataTable = async (res) => {
  return await getHospitalPageList({ ...res, ...getFieldsValue() });
}
function fetchSuccess() {
  // 数据请求成功，设置索引
  currentIndex.value =
    (actionRef.value.pagination.current - 1) *
    actionRef.value.pagination.pageSize;
}

const loadHosTypeData = async () => {
  let dicts = await getDictByDictCode('Hostype')
  hostypeDictOptions.value = dicts.map((item) => {
    return { label: item.name, value: item.value }
  })
}

const loadProvinceData = async () => {
  let dicts = await getDictByDictCode('Province')
  provinceDictOptions.value = dicts.map((item) => {
    return { label: item.name, value: item.value }
  })
}

const getCityData = async () => {
  // 获取省编码
  const { provinceCode } = getFieldsValue()
  console.log(provinceCode);
  let dicts = await findChildData(provinceCode)
  cityDictOptions.value = dicts.map((item) => {
    return { label: item.name, value: item.value }
  })
}

// 刷新表格
function reloadTable() {
  actionRef.value.reload();
}

// 查询提交方法
function handleSubmit() {
  reloadTable();
}

// 查询重置方法
function handleReset() {
  reloadTable();
}

const handleCat = (record) => {
  showDetail.value = true
  currentHospId.value = record.id
}

const handleSchedule = (record) => {
  router.push({ path: `/hospSet/schedule/${record.hoscode}`, query: { hosname: record.hosname }})
}

</script>
